package com.volunteer.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.volunteer.entity.PointRecord;
import com.volunteer.mapper.PointRecordMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 积分服务
 */
@Service
@RequiredArgsConstructor
public class PointService {

    private final PointRecordMapper pointRecordMapper;

    /**
     * 获取用户积分记录
     */
    public IPage<PointRecord> getUserPointRecords(Long userId, int page, int size) {
        Page<PointRecord> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<PointRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PointRecord::getUserId, userId)
                .orderByDesc(PointRecord::getCreateTime);
        return pointRecordMapper.selectPage(pageParam, queryWrapper);
    }

    /**
     * 手动调整积分
     */
    public void adjustPoints(Long userId, Integer points, String description) {
        PointRecord pointRecord = new PointRecord();
        pointRecord.setUserId(userId);
        pointRecord.setPoints(points);
        pointRecord.setType("MANUAL");
        pointRecord.setDescription(description);
        pointRecordMapper.insert(pointRecord);
    }

    /**
     * 获取用户总积分
     */
    public Integer getUserTotalPoints(Long userId) {
        LambdaQueryWrapper<PointRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PointRecord::getUserId, userId);
        return pointRecordMapper.selectList(queryWrapper).stream()
                .mapToInt(PointRecord::getPoints)
                .sum();
    }
}

